package com.online.controller;

import com.faneui.common.bean.BaseResp;
import com.faneui.common.exception.BusinessException;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.online.dal.dao.OrderDAO;
import com.online.dal.dao.OrderDetailDAO;
import com.online.dal.model.Order;
import com.online.dal.model.OrderDetail;
import com.online.dal.model.Product;
import com.online.dal.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("sale")
public class SaleController {

    @Autowired
    private OrderDAO orderDAO;

    @Autowired
    private OrderDetailDAO orderDetailDAO;

    @Autowired
    private HttpSession httpSession;

    @RequestMapping(value = "", method = RequestMethod.GET)
    public ModelAndView indexOfAll() throws Exception {
        ModelAndView mv = new ModelAndView("order");
        User u = (User) httpSession.getAttribute("user");//从会话中获取user对象赋值给u对象


        String key = "productList";

        //从会话中获取productList对象赋值给声明的productList队列对象
        List<Map<String, Object>> productList = (List<Map<String, Object>>) httpSession.getAttribute(key);
        if(u == null || productList == null) {
            mv = new ModelAndView("index");
            mv.addObject("msg", "购物车为空或用户未登录，不能进行结算");
            return mv;
        }
        //生成一个自定义订  单
        Order order = new Order();
        order.setTotal_price(0d);
        order.setsDate(new Date());
        order.setStatus("待支付");
        order.setUser_id(u.getId());
        orderDAO.insert(order);//将生成的订单数据插入到torder表中

        Double total = 0d;

        if (productList != null) {
            for (Map<String, Object> map : productList) {//循productList队列对象赋值给map对象
                OrderDetail od = new OrderDetail();//声明一个od空间对象
                //给声明的对象的属性赋值
                od.setOrder_id(order.getId());
                od.setProduct_id((Integer) map.get("product_id"));
                od.setPrice((Double) map.get("price"));
                od.setNum((Integer) map.get("num"));
                orderDetailDAO.insert(od);

                total = total + (od.getNum() * od.getPrice());
            }
        }

        order.setTotal_price(total);
        orderDAO.updateById(order);//对torder表中插入的order对象数据进行数据更新

        httpSession.removeAttribute(key);//将会话中的productList对象（购物车）删除

//        Order para = new Order () ;
//        para.setUser_id(u.getId());
//        List<Order> orderList = orderDAO.queryByModel(para) ;
//
//        mv.addObject("orderList", orderList);
//        return mv;

        return new ModelAndView("redirect:/order");
    }
}
